<?php

namespace app\admin\controller\user;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="用户分仓")
 */
class Bucket extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\UserBucket();
        
    }
    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();

            $admin = session('admin');//
            $param = [];
            if(!empty($admin['uid'])){
                $param['id'] = $admin['uid'];
            }

            $count = $this->model
                ->where($where)
                ->where($param)
                ->count();
            $list = $this->model
                ->where($where)
                ->where($param)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();

            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];

            return json($data);
        }
        return $this->fetch();
    }

    // 查看成员   ok
    public function viewuser(){
        // zy
//        $id = $this->request->request("id");
//
//        $userlist = json_decode($this->model->find($id)['members'],true);
//
//        foreach($userlist as $key =>$val){
//            $menlist[] = Db::name("user")->find($val);
//        }

        // wtt
        $id = $this->request->request("id");
        $buck = $this->model->find($id);
        $buck_ids = $buck->members ;
        $menlist = Db::name("user")->field("*")->where('id', 'in', $buck_ids )->select();
        $this->assign("list", $menlist);
        return $this->fetch();
    }

    // 创建分仓
    // TODO  新规则, 1个项目=1个分仓, 可在部署第一次时保留一个分仓!!! , 暂时不做创建, 但需要同步redis
    public function add(){
        // 参考 user_bucket.createBucket
        // TODO

    }
    // 暂无开发
    public function edit(){}

    // 同步分仓: 1次
    public function sync(){

    }

    // TODO:  新建分仓的同步操作,  暂不做新建分仓, 但需要同步一次 唯一分仓 的相关数据
    public function add_sync(){
//        let users = await mysql.query("SELECT uid,level1_recommender,level2_recommender FROM user WHERE uid>=?", [uid]);
//
//        let members = [uid];
//        let length = 1;
//        function getMembers() {
//            for (let i = 0; i < users.length; i++) {
//                if (members.indexOf(users[i].level1_recommender) > -1 || members.indexOf(users[i].level2_recommender) > -1) {
//                    members.push(users[i].uid);
//                    users.splice(i--, 1);
//                }
//            }
//
//            if (members.length > length) {
//                length = members.length;
//                getMembers();
//            }
//        }
//        getMembers();
//        members = Array.from(new Set(members));
//        try {
//            let sql = "INSERT INTO user_bucket (uid,bucket_name,admin_uid,members) VALUES (?,?,?,?)";
//            let sql_result = await mysql.query(sql, [uid, bucket_name, uid, JSON.stringify(members)]);
//            await mysql.query("UPDATE user SET bucket_id=? WHERE uid IN (?)", [uid, members]);
//
//            // 更新管理员roles
//            await user_bucket.updateAdminRole([1, 2], uid);
//            await base.updateAllUserInfo(members);
//            await base.updateUserInfo(uid, true);
//            res.send(base.result_ok('创建成功'))
//        } catch (err) {
//            res.send(base.result_error('创建失败或分仓已存在', err))
//        }
    }

    /**
     * @NodeAnotation(title="删除分仓")
     * TODO 删除分仓情况复杂, 参照原逻辑, 删除记录后同步redis,以及其他相关数据
     */
    public function delete($id)
    {
        $this->checkPostRequest();
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            // $save = $row->update(['id' => $id, "state" => -1]);
            $save = 1;
            // TODO  删除分仓 是物理删除, 暂不开发,
            // TODO  但需要手动处理相关逻辑 !!!   @zyy @wtt
            // 解释: 如用户 小李 在 D仓, D仓删除, 则需要客户去确认这个用户是否去A仓, 或者增加按钮让客户批量把用户转移到A仓
            $bucket_id = $id ;
            $this->delete_sync($bucket_id);
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * 删除记录后同步redis,以及其他相关数据
     */
    private function delete_sync($bucket_id){
        //    user_bucket.deleteBucket = async (req, res) => {
//    let token_info = await base.checkAdminToken(req);
//    if (token_info.res_code < 0 || token_info.data.roles.indexOf(1) == -1) {
//    res.send(base.result_error("登录失败"));
//    return;
//    }
//    let user_info = token_info.data;
//
//        let bucket_id = parseInt(req.body.bucket_id);
//        if (!(bucket_id > 0)) {
//            res.send(base.result_error("分仓id错误"));
//            return;
//        }
//        let members = await mysql.query("SELECT * FROM user WHERE bucket_id=?", [bucket_id]);
//        members = members.map(m => {
//        return m.uid;
//    });
//        let sql = "DELETE FROM user_bucket WHERE uid=?";
//        let sql_result = await mysql.query(sql, [bucket_id]);
//        await mysql.query("UPDATE user SET bucket_id=0 WHERE bucket_id=?", [bucket_id]);
//        await user_bucket.updateAdminRole([1], bucket_id);
//        await base.updateUserInfo(bucket_id, true);
//        await redis.Client2.del(`${KEYS.BUCKET_GOODS_LIST}${bucket_id}`);
//        await base.updateAllUserInfo(members);
//        res.send(base.result_ok('删除成功'));
//    };
    }


    /**
     * 更新管理员权限
     * @param {*} roles
     * @param {*} uid
     */
    private function updateAdminRole(){}
//    user_bucket.updateAdminRole = async (roles, uid) => {
//    try {
//    await mysql.query("UPDATE user SET roles=? WHERE uid=?", [JSON.stringify(roles), uid]);
//    } catch (err) {
//    console.log(err);
//    }
//    };

    // 分仓获取分仓成员  TODO  优先级稍次要
    public function getBucketMembers(){

//        let bucket_id = parseInt(req.body.bucket_id);
//        if (!(bucket_id > 0)) {
//            res.send(base.result_error("分仓id错误"));
//            return;
//        }
//
//
//        let bucket = await mysql.query("SELECT * FROM user_bucket WHERE uid=?", [bucket_id]);
//
//            if (bucket.length == 0) {
//                res.send(base.result_ok('ok', []))
//                return;
//            }
//
//            let members = JSON.parse(bucket[0].members);
//            let sql = "SELECT avatar,nickname,phone,payee_name,payee_bankno,payee_bankname,wxpay_img,alipay_img FROM user WHERE uid in (?)";
//            let sql_result = await mysql.query(sql, [members]);
//
//            res.send(base.result_ok('ok', sql_result))
//            return;
    }

    /**
     * 设置分仓管理员
     * @param {*} req
     * @param {*} res
     */
    public function setBucketAdmin(){
//        user_bucket.setBucketAdmin = async (req, res) => {
//            let token_info = await base.checkAdminToken(req);
//            if (token_info.res_code < 0 || token_info.data.roles.indexOf(1) == -1) {
//                res.send(base.result_error("登录失败"));
//                return;
//            }
//            let user_info = token_info.data;
//
//            let bucket_id = parseInt(req.body.bucket_id);
//            if (!(bucket_id > 0)) {
//                res.send(base.result_error("分仓id错误"));
//                return;
//            }
//
//            let admin_uid = parseInt(req.body.admin_uid);
//            if (!(admin_uid > 0)) {
//                res.send(base.result_error("管理员id错误"));
//                return;
//            }
//
//            await user_bucket.updateAdminRole([1, 2], admin_uid);
//
//            let sql = "UPDATE user_bucket SET admin_uid=? WHERE uid=?";
//            let sql_result = await mysql.query(sql, [admin_uid, bucket_id]);
//            res.send(base.result_ok('ok'))
//        };
    }

    /**
     * 设置/取消管理员
     */
    public function setAdmin(){
//        let isadmin = parseInt(req.body.isadmin);
//    if (isadmin != 0 && isadmin != 1) {
//        res.send(base.result_error("isadmin参数错误"));
//        return;
//    }
//
//    let uid = parseInt(req.body.uid);
//    if (!(uid > 0)) {
//        res.send(base.result_error("用户id错误"));
//        return;
//    }
//
//    let roles = [];
//    if (isadmin == 1) {
//        roles.push(1);
//    }
//    await user_bucket.updateAdminRole(roles, uid);

    }

    /**
     * 获取管理员列表
     * @param {*} req
     * @param {*} res
     */
    public function getAdminUserList(){
//        user_bucket.getAdminUserList = async (req, res) => {
//            let token_info = await base.checkAdminToken(req);
//    if (token_info.res_code < 0 || token_info.data.roles.indexOf(1) == -1) {
//        res.send(base.result_error("登录失败"));
//        return;
//    }
//    let user_info = token_info.data;
//
//
//        let sql = `SELECT a.uid,a.nickname,a.avatar,a.phone,a.bucket_id,b.bucket_name
//        FROM user a
//        LEFT JOIN user_bucket b ON a.uid=b.admin_uid
//        WHERE a.roles=? AND a.state > -1`;
//        let sql_result = await mysql.query(sql, [JSON.stringify([1])]);
//        res.send(base.result_ok('ok', sql_result))
//    };
    }

    // TODO  管理员权限, 翻译php后如何实现的? 是否可以忽略原系统逻辑?    @zyy @wtt



}